package hk.linkcredit.walletservice.utils.core;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * spring redis 工具类
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
@Slf4j
public class RedisCache {

    /**
     * 锁超时时间，防止线程在入锁以后，无限的执行等待
     */
    private static final int LOCK_EXPIRE_MSECS = 60 * 1000;

    /**
     * 默认缓存超时时间
     */
    private static final int CACHE_EXPIRE_MSECS = 300;

    //账户锁
    //获取客户账户锁的重试次数
    public static final int CUST_ACCOUNT_LOCK_REGET_COUNT = 3;

    //获取客户账户锁繁忙等待时间
    public static final int CUST_ACCOUNT_LOCK_SLEEP_TIME = 4 * 1000;

    public static final long LOCK_MAX_WAIT_TIME = (10 * 1000);

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public <T> void setCache(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value, CACHE_EXPIRE_MSECS, TimeUnit.SECONDS);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 加锁
     *
     * @param key       redis key
     * @param lockvalue 全局锁ID 用于删除锁，删除自己的锁问题（但是会出现其他问题）@author
     * @return true:加锁成功，false，加锁失败
     */
    public boolean lock(String key, String lockvalue) {
        //public boolean lock(String key) {
//        long expires = System.currentTimeMillis() + LOCK_EXPIRE_MSECS;
//        String expiresStr = String.valueOf(expires);// 这个时间是用于B线程进行等待获取锁的倒计时

        //如果没有就设置返回加锁成功
        //Boolean result = redisTemplate.opsForValue().setIfAbsent(key, expiresStr, LOCK_EXPIRE_MSECS, TimeUnit.MILLISECONDS);
        return redisTemplate.opsForValue().setIfAbsent(key, lockvalue, LOCK_EXPIRE_MSECS, TimeUnit.MILLISECONDS);
//        if (result) {
//            return true;
//        }

        // 如果锁存在获取锁的过期时间
//        String oldExpireTimeStr = (String) redisTemplate.opsForValue().get(key);
//        if (null != oldExpireTimeStr) {
//            Long oldExpireTime = Long.parseLong(oldExpireTimeStr);
//            if (oldExpireTime < System.currentTimeMillis()) {
//                //超时过期
//                long newExpireTime = System.currentTimeMillis() + LOCK_EXPIRE_MSECS;
//
//                //获取原来key键对应的值并重新赋新值。
//                long currentExpireTime = Long.parseLong((String) redisTemplate.opsForValue().getAndSet(key, String.valueOf(newExpireTime)));//上一次设定的过期时间
//
//                //两个上一次的过期时间其实无条件相等
//                if (currentExpireTime == oldExpireTime) {
//                    return true;
//                }
//            }
//        }
        //return false;
    }

    /**
     * 释放锁
     *
     * @param lockKey
     * @param lockKey
     */
    //public void unLock(String lockKey) {
    public void unLock(String lockKey, String lockvalue) {
        if (lockvalue.equals(redisTemplate.opsForValue().get(lockKey))) {
            redisTemplate.opsForValue().getOperations().delete(lockKey);
        }
    }

    /**
     * * 对一个 key-value 的值进行加减操作, * 如果该 key 不存在 将创建一个key 并赋值该 number * 如果 key 存在,但
     * value 不是长整型 ,将报错 * @param key * @param number
     */
    public Long increment(String key, long number) {
        return redisTemplate.opsForValue().increment(key, number);
    }


    public void functionLock(Consumer f, String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        long start = System.currentTimeMillis();
        f.accept(null);
        log.info("锁占用时间，耗时：" + (System.currentTimeMillis() - start) + " ms");
        lock.unlock();
    }

    /**
     * 加锁
     *
     * @param lockKey
     * @return
     */
    public RLock lock(String lockKey) {
        log.info("开始获取锁 >>> {}", lockKey);
        long start = System.currentTimeMillis();
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        log.info("成功获取锁 >>> {}，耗时：{} ms", lockKey, (System.currentTimeMillis() - start));
        return lock;
    }

    /**
     * 释放锁
     *
     * @param lockKey
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     * 释放锁
     *
     * @param lock
     */
    public void unlock(RLock lock) {
        lock.unlock();
    }

    /**
     * 带超时的锁
     *
     * @param lockKey
     * @param timeout 超时时间   单位：秒
     */
    public RLock lock(String lockKey, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * 带超时的锁
     *
     * @param lockKey
     * @param unit    时间单位
     * @param timeout 超时时间
     */
    public RLock lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey
     * @return
     */
    public boolean tryLock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(LOCK_MAX_WAIT_TIME, LOCK_EXPIRE_MSECS, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public boolean tryLock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(LOCK_MAX_WAIT_TIME, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey
     * @param waitTime  最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey
     * @param unit      时间单位
     * @param waitTime  最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

}
